package com.xyy.ec.pop.api.kingdinggmp.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.security.MessageDigest;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class MD5Util {

    private MD5Util() {
    }

    public static final String encrypt(String s) {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        try {
            byte[] btInput = s.getBytes("UTF-8");
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char[] str = new char[j * 2];
            int k = 0;

            for (int i = 0; i < j; ++i) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 15];
                str[k++] = hexDigits[byte0 & 15];
            }

            return new String(str);
        } catch (Exception var10) {
            var10.printStackTrace();
            return null;
        }
    }

    public static final String encrypt(String dataStr, String secret) {
        if (StringUtils.isBlank(dataStr) || StringUtils.isBlank(secret)) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(dataStr).append("&").append(secret);
        return encrypt(sb.toString());
    }
    public static final String encrypt(Map<String, Object> paramMap, String secret) {
        //log.info("加密参数字符串拼接 paramMap:{}, secret:{}", JSON.toJSONString(paramMap), secret);
        StringBuffer str = new StringBuffer(StringUtils.EMPTY);
        //参数拼接字符串
        String paramStr = StringUtils.EMPTY;
        //字符串加密后的MD5值
        String md5Str = null;
        try {
            if (CollectionUtils.isEmpty(paramMap)) {
                paramStr = str.append("secret=").append(secret).toString();
                md5Str = encrypt(paramStr);
                log.warn("加密参数字符串拼接，参数为空 paramMap:{}, secret:{}, paramStr:{}, md5Str:{}", new Object[]{JSON.toJSONString(paramMap), secret, paramStr, md5Str});
                return md5Str;
            }
            List<Map.Entry<String, Object>> entryList = paramMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
            for (Map.Entry<String, Object> entry : entryList) {
                String key = entry.getKey();
                Object value = entry.getValue();
                if (StringUtils.isBlank(key) || ("sign").equals(key) || isEmpty(value)) {
                    continue;
                }
                str.append(key).append("=").append(JSON.toJSONString(value)).append("&");
            }
            paramStr = str.append("secret=").append(secret).toString();
            //log.info("加密参数字符串拼接，paramMap:{}, secret:{}, paramStr:{}", JSON.toJSONString(paramMap), secret, paramStr);
            md5Str = encrypt(paramStr);
            //log.info("加密参数字符串拼接, paramMap:{}, secret:{}, paramStr:{}, md5Str:{}", new Object[]{JSON.toJSONString(paramMap), secret, paramStr, md5Str});
            return md5Str;
        } catch (Exception e) {
            log.error("加密参数字符串拼接,error. paramMap:{}, secret:{}", JSON.toJSONString(paramMap), secret, e);
            return null;
        }
    }

    /**
     * 校验参数Map的value值是否为空
     *
     * @param obj
     * @return
     */
    private static boolean isEmpty(Object obj) {
        if (obj instanceof String) {
            String str = (String) obj;
            if (StringUtils.isBlank(str)) {
                return true;
            }
        } else if (obj instanceof Collection) {
            Collection col = (Collection) obj;
            if (CollectionUtils.isEmpty(col)) {
                return true;
            }
        } else if (obj instanceof Map) {
            Map map = (Map) obj;
            if (CollectionUtils.isEmpty(map)) {
                return true;
            }
        } else if (obj instanceof Object[]) {
            Object[] array = (Object[]) obj;
            if (array == null || array.length <= 0) {
                return true;
            }
        } else {
            if (obj == null) {
                return true;
            }
        }
        return false;
    }


    public static void main(String[] args) {
        System.out.println(encrypt("ybm10010"));
        Map<String, Object> map = new HashMap<>();
        map.put("b", "2");
        map.put("d", "who");
        map.put("a", JSON.toJSONString(Lists.newArrayList(2, 1, 4)));
        map.put("c", null);
        map.put("ab", "are");
        map.put("abc", "you");
        System.out.println(encrypt(map, "111"));

    }
}
